package com.xiaoxi.userserver.controller.user;

import com.xiaoxi.common.constant.enumeration.statuscode.user.LoginUserEnums;
import com.xiaoxi.logaspectcommon.common.annotation.LoginLog;
import com.xiaoxi.logaspectcommon.common.annotation.OperationLog;
import com.xiaoxi.logaspectcommon.common.constant.OperationConstants;
import com.xiaoxi.common.constant.enumeration.statuscode.other.CommonEnums;
import com.xiaoxi.common.constant.enumeration.statuscode.system.LoginSystemEnums;
import com.xiaoxi.common.constant.enumeration.statuscode.user.RegisterUserEnums;
import com.xiaoxi.common.exception.BMSException;
import com.xiaoxi.common.response.ApiResponse;
import com.xiaoxi.common.util.RSAUtils;
import com.xiaoxi.domain.user.BMSUser;
import com.xiaoxi.feign.codeimageserver.CodeImageServer;
import com.xiaoxi.userserver.domain.vo.user.BMSUserLoginVO;
import com.xiaoxi.userserver.domain.vo.user.BMSUserPasswordChangeVO;
import com.xiaoxi.userserver.service.user.BMSUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName BMSUserController
 * @Description 用户登录注册等操作
 * @Author xiaoxi
 * @Date 2022/4/24 14:26
 * @Version 1.0
 */
@RestController
@RequestMapping("/user/api/v1")
@Slf4j
public class BMSUserController {

    @Resource
    private BMSUserService bmsUserService;

    @Resource
    private CodeImageServer codeImageServer;

    @Value("${bms.xiaoxi.RSA-private-key}")
    private String rsaPrivateKey;

    @LoginLog(param = "bmsUserLoginVO")
    @PostMapping("login")
    public ApiResponse userLogin(@RequestBody BMSUserLoginVO bmsUserLoginVO) {

        // 校验验证码是否正确
        ApiResponse apiResponse = codeImageServer.checkVerificationCode(bmsUserLoginVO.getVerificationCodeId(), bmsUserLoginVO.getVerificationCode());
        log.info(apiResponse.toString());
        if (!"200".equals(apiResponse.getCode())) {
            return apiResponse;
        }

        String username = bmsUserLoginVO.getUsername();
        String password;
        try {
            password = RSAUtils.decryptByPrivateKey(bmsUserLoginVO.getPassword(), rsaPrivateKey);
        } catch (Exception e) {
            log.error("密钥失效：{}", e.getMessage());
            return ApiResponse.ofEnum(LoginSystemEnums.PRIVATE_KEY_FAIL);
        }

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ApiResponse.ofEnum(LoginUserEnums.PLEASE_CHECK_YOUR_LOGIN_INFORMATION);
        }

        Map<String, String> map = null;
        try {
            map = bmsUserService.userLogin(username, password);
        } catch (BMSException e) {
            log.error("登录异常：{}", e.getMessage());
            return ApiResponse.ofException(e);
        }

        return ApiResponse.ofSuccess(map);

    }

    /**
     * 修改密码
     *
     * @param bmsUserPasswordChangeVO 修改密码信息
     * @return
     */
    @OperationLog(operation = OperationConstants.CODE_CHANGE_PASSWORD)
    @PostMapping("changeUserPassword")
    public ApiResponse changeUserPassword(@RequestBody BMSUserPasswordChangeVO bmsUserPasswordChangeVO) {

        try {
            bmsUserService.changePassword(bmsUserPasswordChangeVO, true);
        } catch (BMSException bmsException) {
            log.error("出现异常：{}", bmsException.getMessage());
            return ApiResponse.ofException(bmsException);
        }

        return ApiResponse.ofSuccess();
    }


    /**
     * 删除用户
     *
     * @param userId 用户编号
     * @return
     */
    @OperationLog(operation = OperationConstants.CODE_DELETE)
    @GetMapping("deleteUserByUserId/{userId}")
    public ApiResponse deleteUserByUserId(@PathVariable Long userId) {
        Boolean deleteStatus = bmsUserService.deleteUserByUserId(userId);
        if (deleteStatus) {
            return ApiResponse.ofSuccess();
        }
        return ApiResponse.ofEnum(LoginSystemEnums.INCORRECT_USER_ID);
    }


    /**
     * 修改用户  启用状态
     *
     * @param userId
     * @return
     */
    @OperationLog(operation = OperationConstants.CODE_ENABLE)
    @GetMapping("enableUserStatus/{userId}")
    public ApiResponse enableUserStatus(@PathVariable Long userId) {
        Boolean enableUserStatus = null;
        try {
            enableUserStatus = bmsUserService.enableUserStatus(userId, null);
        } catch (BMSException e) {
            log.error("发生异常：{}", e.getMessage());
            return ApiResponse.ofException(e);
        }
        if (enableUserStatus) {
            return ApiResponse.ofSuccess();
        } else {
            return ApiResponse.ofEnum(CommonEnums.INFORMATION_OUT_OF_DATE);
        }
    }

    /**
     * 修改用户 锁定状态
     *
     * @param userId
     * @return
     */
    @OperationLog(operation = OperationConstants.CODE_ACCOUNT)
    @GetMapping("accountNonLockedUserStatus/{userId}")
    public ApiResponse accountNonLockedUserStatus(@PathVariable Long userId) {
        Boolean accountNonLockedUserStatus = null;
        try {
            accountNonLockedUserStatus = bmsUserService.accountNonLockedUserStatus(userId, null);
        } catch (BMSException e) {
            log.error("发生异常：{}", e.getMessage());
            return ApiResponse.ofException(e);
        }
        if (accountNonLockedUserStatus) {
            return ApiResponse.ofSuccess();
        } else {
            return ApiResponse.ofEnum(CommonEnums.INFORMATION_OUT_OF_DATE);
        }
    }


    /**
     * 检查用户名重复
     *
     * @param username
     * @param userId
     * @return
     */
    @OperationLog(operation = OperationConstants.CODE_CHECK)
    @GetMapping("checkUsername")
    public ApiResponse checkUsername(String username, Long userId) {

        if (StringUtils.isBlank(username)) {
            return ApiResponse.ofEnum(RegisterUserEnums.PLEASE_INPUT_USERNAME);
        }

        BMSUser bmsUser = bmsUserService.selectOneByUserName(username);
        if (Objects.nonNull(bmsUser) && !bmsUser.getId().equals(userId)) {
            return ApiResponse.ofEnum(RegisterUserEnums.USER_REGISTERED);
        }
        return ApiResponse.ofSuccess();

    }


}
